package com.example.yuanboot.filter;

import cn.hutool.core.codec.Base64;
import cn.hutool.extra.spring.SpringUtil;
import com.example.yuanboot.common.config.datasource.DataSourceHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.web.filter.GenericFilterBean;

import javax.crypto.spec.OAEPParameterSpec;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author qingyan 2021-06-04
 */
@Slf4j
public class PathFilter extends GenericFilterBean {


    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
//        AbstractRoutingDataSource bean = SpringUtil.getBean(AbstractRoutingDataSource.class);
//        log.info("当前数据源：{}", bean.getConnection().getSchema());
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String path = request.getServletPath();
        if (path.endsWith(".html")) {
            path = path.replace(".html", "");
            if (path.startsWith("/")) {
                path = path.replaceFirst("/", "");
            }
            String encode = Base64.encode(path);
            /*
             * 如果没有根路径 /,只会替换最后部分
             */
            request.getRequestDispatcher("/to?path=" + encode).forward(request, servletResponse);
        } else {
            filterChain.doFilter(request, servletResponse);
        }

    }
}
